# @Author   : tan90
# @Time     : 2025/7/3 15:00

from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
    DeleteRowsEvent,
    UpdateRowsEvent,
    WriteRowsEvent
)

mysql_settings = {'host': '180.107.109.102', 'port': 10031, 'user': 'root', 'passwd': 'root@123456!'}

stream = BinLogStreamReader(connection_settings=mysql_settings,
                            server_id=1001,
                            only_schemas=["iot_device"],
                            only_tables=["date_type"],
                            only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent])

try:
    for binlogevent in stream:
        # 打印事件元数据
        print(f"Event type: {type(binlogevent).__name__}")
        print(f"Schema: {binlogevent.schema}, Table: {binlogevent.table}")

        # 处理不同事件类型
        for row in binlogevent.rows:
            if isinstance(binlogevent, WriteRowsEvent):
                print(f"[INSERT] New row: {row['values']}")

            elif isinstance(binlogevent, UpdateRowsEvent):
                print(f"[UPDATE] Before: {row['before_values']}")
                print(f"[UPDATE] After: {row['after_values']}")

            elif isinstance(binlogevent, DeleteRowsEvent):
                print(f"[DELETE] Removed: {row['values']}")

        # 打印当前binlog位置（可用于持久化）
        print(f"Current position: {stream.log_file} {stream.log_pos}")

finally:
    stream.close()  # 重要：关闭连接
